package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Dto.SetmealDto;
import com.itheima.Emtity.Setmeal;
import com.itheima.Emtity.SetmealDish;
import com.itheima.common.CustomException;
import com.itheima.mapper.SetmealMapper;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;

    @Transactional
    @Override
    public boolean savewithDish(SetmealDto setmealDto) {
        //保存套餐表
//    拿出套餐的id
        boolean save = this.save(setmealDto);
        //菜品信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //套餐的id
        Long setmealId = setmealDto.getId();
        setmealDishes.stream().forEach((item) -> {
            item.setSetmealId(setmealId);
        });

        System.out.println(setmealDishes);
        //保存菜品的在多对多表.
        boolean b = setmealDishService.saveBatch(setmealDishes);
        return b;
    }


    /**
     * 删除套餐和套餐菜品表
     *
     * @param ids
     */

    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper();
        //停售的套餐可以删除,销售中的不可以删除
        // ids :1,2,3;
        lambdaQueryWrapper.in(Setmeal::getId, ids);
        // status : 0
        lambdaQueryWrapper.eq(Setmeal::getStatus, 1);
        int count = this.count(lambdaQueryWrapper);
//套餐中只要有一个在售卖都不可以删除.
        if (count > 0) {
            //说明有在售卖的套餐,不可以删除
            throw new CustomException("有正在售卖的套餐");
        }
        //说明可以删除

        //停售的抛出一个业务异常

        //先删除子表数据
//        delete from setmeal_dish where setmeal_id in (1,2,3);
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper1 = new LambdaQueryWrapper();
        lambdaQueryWrapper1.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(lambdaQueryWrapper1);

        //在删除父表.setmeal

        this.removeByIds(ids);
    }
}
